#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define SERV_PORT 55560 
typedef struct sockaddr SA;

void dg_echo(int sockfd, SA* pcliaddr,socklen_t clilen)
{
    int n;
    const int MSG_LEN = 1024;
    socklen_t len;
    char msg[MSG_LEN];

    for(;;)
    {
        len = clilen;
        n = recvfrom(sockfd,msg,MSG_LEN,0,pcliaddr,&len);
        printf("recvfrom--<%s:%d>\n",inet_ntoa(((struct sockaddr_in*)pcliaddr)->sin_addr),ntohs(((struct sockaddr_in*)pcliaddr)->sin_port));

        sendto(sockfd,msg,n,0,pcliaddr,len);
    }
}

int main(int argc, char *argv[])
{
    if(argc != 2){
        printf("Usage : %s <port>\n",argv[0]);
        return -1;
    }
    int sockfd;
    struct sockaddr_in servaddr, cliaddr;

    sockfd = socket(PF_INET,SOCK_DGRAM,0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = PF_INET;
    servaddr.sin_addr.s_addr = htons(INADDR_ANY);
    servaddr.sin_port = htons(atoi(argv[1]));

    bind(sockfd,(SA*)&servaddr,sizeof(servaddr));

    dg_echo(sockfd,(SA*)&cliaddr,sizeof(cliaddr));

    return 0;
}
